import re

from django import http
from django.conf import settings
from django.contrib.auth import login
from django.shortcuts import render, redirect

# Create your views here.
from django.urls import reverse
from django.views import View

from apps.ausers.models import User
from apps.oauth.models import OAuthQQUser, OAuthSinaUser
from apps.oauth.utils import SecretOauth
from meiduo_mall.settings.dev import logger
from utils.response_code import RETCODE


# 判断是否绑定了openid
def is_bind_openid(openid, request):
    try:
        oauth_user = OAuthQQUser.objects.get(openid=openid)
    except Exception as e:
        logger.error(e)
        # 2.未绑定了   ---跳转到 绑定的页面
        context = {'openid': openid}
        # 没绑定---弹出绑定个人信息的 页面
        context = {'openid': SecretOauth().dumps(context)}
        return render(request, 'oauth_callback.html', context)
    else:
        # 1.绑定 --保持登录状态---设置username--cookie--跳转到首页
        user = oauth_user.user
        #   保持登录状态
        login(request, user)
        #   ---设置username--cookie
        response = redirect(reverse('contents:index'))
        # --跳转到首页
        response.set_cookie('username', user.username, max_age=3600 * 24 * 14)

        return response


# QQ 登录--code-->token-->openid
# http://www.meiduo.site:8000/oauth_callback?code=514D2BE5E31DBC30106501CDC03ACD0A&state=None
class QQAuthUserView(View):
    def get(self, request):

        code = request.GET.get('code')
        if not code:
            return http.HttpResponseForbidden('缺少code')

        from QQLoginTool.QQtool import OAuthQQ
        oauth = OAuthQQ(client_id=settings.QQ_CLIENT_ID, client_secret=settings.QQ_CLIENT_SECRET,
                        redirect_uri=settings.QQ_REDIRECT_URI)

        try:
            # code-->token
            access_token = oauth.get_access_token(code)
            # token--->openid
            openid = oauth.get_open_id(access_token)
        except Exception as e:
            logger.error(e)
            return http.HttpResponseServerError('Oauth2.0认证失败!')

        # 判断是否绑定了openid
        response = is_bind_openid(openid, request)
        # 返回前端
        return response

    def post(self, request):
        mobile = request.POST.get('mobile')
        pwd = request.POST.get('password')
        sms_code_client = request.POST.get('sms_code')
        openid = SecretOauth().loads(request.POST.get('openid')).get('openid')

        if not openid:
            return render(request, 'oauth_callback.html', {'openid_errmsg': '无效的openid'})

        # 保存注册数据
        try:
            user = User.objects.get(mobile=mobile)
        except User.DoesNotExist:
            # 用户不存在,新建用户
            user = User.objects.create_user(username=mobile, password=pwd, mobile=mobile)
        else:
            # 如果用户存在，检查用户密码
            if not user.check_password(pwd):
                return render(request, 'oauth_callback.html', {'account_errmsg': '用户名或密码错误'})

        # 绑定用户
        OAuthQQUser.objects.create(
            openid=openid,
            user=user
        )

        # 保持登录状态
        login(request, user)
        response = redirect(reverse('contents:index'))
        response.set_cookie('username', user.username, max_age=3600 * 24 * 15)

        return response


class QQAuthURLView(View):
    def get(self, request):
        # 1.实例化 qq认证类
        from QQLoginTool.QQtool import OAuthQQ
        oauth_qq = OAuthQQ(
            client_secret=settings.QQ_CLIENT_SECRET,
            client_id=settings.QQ_CLIENT_ID,
            redirect_uri=settings.QQ_REDIRECT_URI
        )

        # 2.获取登录网址
        login_url = oauth_qq.get_qq_url()

        # 3.返回给前端
        return http.JsonResponse({'code': RETCODE.OK, 'errmsg': 'OK', 'login_url': login_url})




class WeiboAuthURLView(View):
    def get(self, request):
        # 1.实例化
        from utils.sinaweibopy3 import APIClient
        client = APIClient(app_key=settings.APP_KEY,
                                        app_secret=settings.APP_SECRET,
                                        redirect_uri=settings.REDIRECT_URI
                                        )
        # 2.获取登录网址
        login_url = client.get_authorize_url()

        # 3.返回给前端
        return http.JsonResponse({'code': RETCODE.OK, 'errmsg': 'OK', 'login_url': login_url})

class WeiboAuthUserView(View):
    def get(self, request):
        code = request.GET.get('code')
        if not code:
            return http.HttpResponseForbidden('缺少code')

        from utils.sinaweibopy3 import APIClient
        client = APIClient(app_key=settings.APP_KEY,
                           app_secret=settings.APP_SECRET,
                           redirect_uri=settings.REDIRECT_URI
                           )

        try:
            result = client.request_access_token(code)
            access_token = result.access_token
            uid = result.uid
        except Exception as e:
            logger.error(e)
            return http.HttpResponseServerError('Oauth2.0认证失败!')

        # 判断是否绑定了token
        response = is_bind_uid(uid, request)
        # 返回前端
        return response

    def post(self, request):
        # 1.接收参数
        mobile = request.POST.get('mobile')
        pwd = request.POST.get('password')
        sms_code_client = request.POST.get('sms_code')
        _uid=request.POST.get('uid')
        uid = SecretOauth().loads(request.POST.get('uid')).get('uid')
        # 2.校验参数
        if not all([mobile, pwd, sms_code_client, uid]):
            return render(request, 'sina_callback.html', {'uid_errmsg': '缺少参数'})
        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return render(request, 'sina_callback.html', {'uid_errmsg': '手机号错误'})
        if not re.match(r'^[0-9A-Za-z]{8,20}$', pwd):
            return render(request, 'sina_callback.html', {'uid_errmsg': '密码错误'})
        if not sms_code_client:
            return render(request, 'sina_callback.html', {'uid_errmsg': '图片验证码失效'})
        if not uid:
            return render(request, 'sina_callback.html', {'uid_errmsg': '无效的uid'})

        # 3.保存注册数据
        try:
            user = User.objects.get(mobile=mobile)
        except User.DoesNotExist:
            # 用户不存在,新建用户
            user = User.objects.create_user(username=mobile, password=pwd, mobile=mobile)
        else:
            # 如果用户存在，检查用户密码
            if not user.check_password(pwd):
                return render(request, 'sina_callback.html', {'account_errmsg': '用户名或密码错误'})

        # 绑定用户
        OAuthSinaUser.objects.create(
            uid=uid,
            user=user
        )

        # 保持登录状态
        login(request, user)
        response = redirect(reverse('contents:index'))
        response.set_cookie('username', user.username, max_age=3600 * 24 * 15)

        return response

def is_bind_uid(uid, request):
    try:
        oauth_user = OAuthSinaUser.objects.get(uid=uid)
    except Exception as e:
        logger.error(e)
        # 2.未绑定了   ---跳转到 绑定的页面
        context = {'uid': uid}
        # 没绑定---弹出绑定个人信息的 页面
        context = {'uid': SecretOauth().dumps(context)}
        return render(request, 'sina_callback.html', context)
    else:
        # 1.绑定 --保持登录状态---设置username--cookie--跳转到首页
        user = oauth_user.user
        #   保持登录状态
        login(request, user)
        #   ---设置username--cookie
        response = redirect(reverse('contents:index'))
        # --跳转到首页
        response.set_cookie('username', user.username, max_age=3600 * 24 * 14)

        return response